package com.jushu.storbox;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jushu.storbox.actions.ActionShare;
import com.jushu.storbox.actions.FileAction;
import com.jushu.storbox.actions.FolderAction;
import com.jushu.storbox.actions.NodeAction;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.IntentConstant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileType;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.view.resolve.TargetSearchDisplayResolve;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

/**
 * <font color="green"> how to use this activity like this template:</br></font>
 * Intent intent = new Intent(context, TargetFolderBrowserActivity.class);</br>
 * Bundle bundle = new Bundle();</br> <font color="blue">
 * bundle.putString(IntentConstant.INTENT_TARGET_RESOURCE_OWNER,
 * saveToOwnerId);</br> others....</br> </font> intent.putExtra(<font
 * color="red">IntentConstant.INTENT_SEARCH_TARGET_DATA</font>, bundle);</br>
 * startActivityForResult(intent,
 * IntentConstant.INTENT_REQUEST_SEARCH_TARGET);</br> </br> <font color="green">
 * the result like this template:</br></font> Bundle bundle =
 * intent.getBundleExtra(<font
 * color="red">IntentConstant.INTENT_SEARCH_TARGET_DATA</font>);</br> <font
 * color="blue"> String saveToSourceId =
 * bundle.getString(IntentConstant.INTENT_TARGET_RESOURCE_ID);</br> String
 * saveToOwnerId =
 * bundle.getString(IntentConstant.INTENT_TARGET_RESOURCE_OWNER);</br>
 * others....</br> </font> </br> </br> <font color="blue">others</font> is what
 * you want to translate.
 */
public class TargetFolderBrowserActivity extends BaseTitleActivity {

	TargetSearchDisplayResolve displayResolve = null;
	PullToRefreshListView dataShowView;

	String currentFolderId = Constant.ROOT_FOLDER_ID;
	String currentOwnerId = "";

	Intent intent = null;
	Bundle bundle = null;

	ArrayList<FileFolderInfo> successList = new ArrayList<FileFolderInfo>();

	Boolean moveTargetIsSelfSub = false;

	ClientExceptionRelateHandler msgHandler = new ClientExceptionRelateHandler() {
		public void handleMessage(Message msg) {
			if (intent == null) {
				intent = new Intent();
			}
			if (bundle == null) {
				bundle = new Bundle();
			}
			switch (msg.what) {

			case UiConstant.NODES_ACTION_MOVE_ITEM_SUCCESS:// 批量移动中某一个移动成功
				FileFolderInfo info1 = (FileFolderInfo) msg.obj;
				successList.add(info1);
				break;

			case UiConstant.NODES_ACTION_MOVE_ALL_SUCCESS:// 批量移动中所有移动成功
															// successList
				bundle.putSerializable(IntentConstant.INTENT_DATA_EXTENDS_1, successList);
				intent.putExtra(IntentConstant.INTENT_SEARCH_TARGET_DATA, bundle);
				setResult(UiConstant.NODES_ACTION_MOVE_ALL_SUCCESS, intent);
				finish();
				break;

			case UiConstant.NODES_ACTION_MOVE_SOME_SUCCESS:// 批量移动中部分移动成功（突然断网了）
															// successList
				bundle.putSerializable(IntentConstant.INTENT_DATA_EXTENDS_1, successList);
				intent.putExtra(IntentConstant.INTENT_SEARCH_TARGET_DATA, bundle);
				setResult(UiConstant.NODES_ACTION_MOVE_SOME_SUCCESS, intent);
				finish();
				break;

			case UiConstant.NODES_ACTION_MOVE_CANCAL:// 批量移动中取消自动重命名
				bundle.putSerializable(IntentConstant.INTENT_DATA_EXTENDS_1, successList);
				intent.putExtra(IntentConstant.INTENT_SEARCH_TARGET_DATA, bundle);
				setResult(UiConstant.NODES_ACTION_MOVE_CANCAL, intent);
				finish();
				break;

			case UiConstant.NODES_ACTION_MOVE_TAGET_SAME_PARENT:// 批量移动中目标文件夹和源文件的父目录相同
				Toast.makeText(TargetFolderBrowserActivity.this, R.string.move_target_no_change, Toast.LENGTH_SHORT).show();
				break;

			case UiConstant.NODE_ACTION_MOVE_CANCEL: // 单个文件|文件夹移动 取消自动重命名
				setResult(UiConstant.NODE_ACTION_MOVE_CANCEL, intent);
				finish();
				break;

			case UiConstant.NODE_ACTION_MOVE_SUCCESS:// 单个文件|文件夹移动成功
				FileFolderInfo info = (FileFolderInfo) msg.obj;
				bundle.putSerializable(IntentConstant.INTENT_DATA_EXTENDS_1, info);
				intent.putExtra(IntentConstant.INTENT_SEARCH_TARGET_DATA, bundle);
				setResult(UiConstant.NODE_ACTION_MOVE_SUCCESS, intent);
				finish();
				break;

			case MessageCode.TRANSFER_TO_MY_TEAM_SUCCESS: // 单个文件转存到团队空间成功
				setResult(MessageCode.TRANSFER_TO_MY_TEAM_SUCCESS, intent);
				finish();
				break;

			case UiConstant.NODES_ACTION_COPY_TEMA_CANCEL: // 批量文件转存到团队空间成功(取消重命名)
				setResult(UiConstant.NODES_ACTION_COPY_TEMA_CANCEL, intent);
				finish();
				break;
			case UiConstant.NODES_ACTION_COPY_ALL_SUCCESS: // 批量文件转存到团队空间成功

				setResult(UiConstant.NODES_ACTION_COPY_ALL_SUCCESS, intent);
				finish();
				break;

			case UiConstant.NODES_ACTION_COPY_SOME_SUCCESS:// 批量文件转存到团队空间部分成功
				setResult(UiConstant.NODES_ACTION_COPY_SOME_SUCCESS, intent);
				finish();
				break;

			case UiConstant.SHARE_ACTION_SAVE_SHARE_RESOURCE: // 收到的共享保存到我的云盘成功
																// |团队空间转存到我的云盘取消自动重命名

				setResult(UiConstant.SHARE_ACTION_SAVE_SHARE_RESOURCE, intent);
				finish();
				break;

			case UiConstant.SHARE_ACTION_SAVE_CANCEL:// 收到的共享保存到我的云盘，取消自动重名名
														// |团队空间转存到我的云盘取消自动重命名|文件转存到团队空间
				setResult(UiConstant.SHARE_ACTION_SAVE_CANCEL, intent);
				finish();
				break;

			case MessageCode.MOVE_SUCCESS: // 团队空间移动成功
				setResult(MessageCode.MOVE_SUCCESS, intent);
				finish();
				break;
			case MessageCode.TRANSFER_TO_MY_FILE_SUCCESS: // 团队空间转存到我的云盘成功
				setResult(MessageCode.TRANSFER_TO_MY_FILE_SUCCESS, intent);
				finish();
				break;

			default:
				super.handleMessage(msg);
			}
		}

		@Override
		public Context getContext() {
			return TargetFolderBrowserActivity.this;
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_target_folder_browser);

		switchTypeTwo();
		rightOperation.setText("确定");
		dataShowView = (PullToRefreshListView) findViewById(R.id.file_action_content_list);

		intent = getIntent();
		if (intent != null) {
			bundle = intent.getBundleExtra(IntentConstant.INTENT_SEARCH_TARGET_DATA);
		}
		Log.i("test", "bundle = " + bundle);
		String titleName = "";
		if (bundle != null) {
			currentOwnerId = bundle.getString(IntentConstant.INTENT_TARGET_RESOURCE_OWNER);
			titleName = bundle.getString(IntentConstant.INTENT_TITLE_NAME);

			if (!StringUtil.isBlank(currentOwnerId)) {

				displayResolve = new TargetSearchDisplayResolve(this, currentOwnerId, titleName) {
					protected void onItemOpend(String folderId, String folderName) {
						currentFolderId = folderId;
						if (folderName != null){
							setTitleText(folderName);
						}
					}

					@Override
					public void openParentFolder() {
						super.openParentFolder();
						if (!moveTargetIsSelfSub) {
							return;
						}// move Target Is SelfSub
						ArrayList<FileFolderInfo> datas = (ArrayList<FileFolderInfo>) bundle.getSerializable(UiConstant.NODE_MOVE_DATAS);
						if (null != datas && !datas.isEmpty()) {
							for (FileFolderInfo data : datas) {
								if (data.getIsFile() == FileType.FOLDER_TYPE_VALUE && data.getId().equals(currentFolderId)) {
									moveTargetIsSelfSub = false;
								}
							}
						}
					}

					@Override
					protected void openFolder(int index, FileFolderInfo info) {
						super.openFolder(index, info);
						if (moveTargetIsSelfSub) {
							return;
						}
						ArrayList<FileFolderInfo> datas = (ArrayList<FileFolderInfo>) bundle.getSerializable(UiConstant.NODE_MOVE_DATAS);
						if (null != datas && !datas.isEmpty()) {
							// datas.contains(info);
							for (FileFolderInfo data : datas) {
								if (data.getIsFile() == FileType.FOLDER_TYPE_VALUE && data.getId().equals(info.getId())) {
									moveTargetIsSelfSub = true;
									break;
								}
							}
						}
					}
				};

				displayResolve.initComponent(dataShowView);
				displayResolve.binddingAdapter();
			}
		}

		if (StringUtil.isBlank(titleName)) {
			currentTitle.setText(R.string.my_cloud_drive);
		} else {
			currentTitle.setText(titleName);
		}
	}

	@Override
	protected void onLeftClicked(View clickView) {

		if (StringUtil.isBlank(currentOwnerId)) {
			if (intent == null) {
				intent = new Intent();
			}
			setResult(IntentConstant.INTENT_RESPONSE_SEARCH_TARGET_NULL, intent);
			finish();
			return;
		}

		if (displayResolve.getHistoryStack().size() > 1) {
			displayResolve.openParentFolder();
		} else {
			if (intent == null) {
				intent = new Intent();
			}
			setResult(IntentConstant.INTENT_RESPONSE_SEARCH_TARGET_NULL, intent);
			finish();
		}
	}

	@Override
	protected void onRightClicked(View clickView) {

		if (StringUtil.isBlank(currentOwnerId)) {

			if (intent == null) {
				intent = new Intent();
			}
			setResult(IntentConstant.INTENT_RESPONSE_SEARCH_TARGET_NULL, intent);
			finish();

		} else {

			switch (bundle.getInt(IntentConstant.INTENT_COMEFROM_REQUEST)) {
			case (IntentConstant.INTENT_REQUEST_MOVEFILE): // 来自文件的移动请求
				fileMoveAction();
				break;

			case IntentConstant.INTENT_REQUEST_TRANSLATEFILE: // 来自文件的转存到团队空间请求
				fileTranslateTema();
				break;

			case IntentConstant.INTENT_REQUEST_SAVESHARE: // 来自分享保存到我的网盘
				shareSaveAction();
				break;

			case IntentConstant.INTENT_REQUEST_MOVETEAM: // 来自团队空间的移动请求
				teamMoveAction();
				break;

			case IntentConstant.INTENT_REQUEST_TRANSFERTEAM: // 来自团队空间转存到我的云盘请求
				teamTransfer();
				break;

			default:
				Toast.makeText(TargetFolderBrowserActivity.this, "其他请求", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	}

	public void setTitleText(String title) {
		currentTitle.setText(title);
	}

	void fileMoveAction() {
		ArrayList<FileFolderInfo> datas = (ArrayList<FileFolderInfo>) bundle.getSerializable(UiConstant.NODE_MOVE_DATAS);

		if (datas == null || datas.isEmpty()) { /* 单个文件、文件夹的移动 */
			FileFolderInfo info = (FileFolderInfo) bundle.getSerializable(IntentConstant.INTENT_DATA_EXTENDS_1);

			if (StringUtil.isNotBlank(currentFolderId) && StringUtil.isNotBlank(currentOwnerId)) {
				if (info.getIsFile() == FileType.File.value()) {

					new FileAction().moveFile(TargetFolderBrowserActivity.this, UiConstant.NODE_ACTION_MOVE_SUCCESS, info, currentFolderId, currentOwnerId,
							msgHandler);
				} else if (info.getIsFile() == FileType.Folder.value()) {

					new FolderAction().moveFolder(TargetFolderBrowserActivity.this, UiConstant.NODE_ACTION_MOVE_SUCCESS, info, currentFolderId, currentOwnerId,
							msgHandler);
				}
			} else {
				LogUtil.e(TAG, "some fileds is empty!");
			}

		} else { /* 批量移动 */

			if (moveTargetIsSelfSub) { // 目标文件夹是源文件夹的子文件夹
				Toast.makeText(TargetFolderBrowserActivity.this, R.string.move_target_is_selfsub, Toast.LENGTH_SHORT).show();
				return;
			} else {
				new NodeAction().moveNodes(TargetFolderBrowserActivity.this, msgHandler, IntentConstant.INTENT_RESPONSE_SEARCH_TARGET_VALUE, datas,
						currentFolderId, currentOwnerId);
			}
		}
	}

	void shareSaveAction() {
		Bundle bundle = intent.getBundleExtra(IntentConstant.INTENT_SEARCH_TARGET_DATA);
		int sourceType = bundle.getInt(IntentConstant.INTENT_SOURCE_RESOURCE_TYPE);
		String sourceResourceID = bundle.getString(IntentConstant.INTENT_SOURCE_RESOURCE_ID);
		String sourceResourceOwnerID = bundle.getString(IntentConstant.INTENT_SOURCE_RESOURCE_OWNER);

		if (StringUtil.isNotBlank(sourceResourceID) && StringUtil.isNotBlank(sourceResourceOwnerID) && StringUtil.isNotBlank(currentFolderId)
				&& StringUtil.isNotBlank(currentOwnerId)) {
			if (sourceType == FileType.File.value()) {

				new ActionShare().copyShareFile(TargetFolderBrowserActivity.this, UiConstant.SHARE_ACTION_SAVE_SHARE_RESOURCE, sourceResourceOwnerID,
						sourceResourceID, currentOwnerId, currentFolderId, msgHandler);
			} else if (sourceType == FileType.Folder.value()) {

				new ActionShare().copyShareFolder(TargetFolderBrowserActivity.this, UiConstant.SHARE_ACTION_SAVE_SHARE_RESOURCE, sourceResourceOwnerID,
						sourceResourceID, currentOwnerId, currentFolderId, msgHandler);
			}
		} else {
			LogUtil.e(TAG, "some fileds is empty!");
		}
	}

	void teamMoveAction() {
		int sourceType = bundle.getInt(IntentConstant.INTENT_SOURCE_RESOURCE_TYPE);
		FileFolderInfo info = (FileFolderInfo) bundle.getSerializable(IntentConstant.INTENT_DATA_EXTENDS_1);
		if (StringUtil.isNotBlank(currentFolderId) && StringUtil.isNotBlank(currentOwnerId)) {
			if (sourceType == FileType.File.value()) {

				new FileAction().moveFile(TargetFolderBrowserActivity.this, MessageCode.MOVE_SUCCESS, info, currentFolderId, currentOwnerId, msgHandler);
			} else if (sourceType == FileType.Folder.value()) {

				new FolderAction().moveFolder(TargetFolderBrowserActivity.this, MessageCode.MOVE_SUCCESS, info, currentFolderId, currentOwnerId, msgHandler);
			}
		} else {
			LogUtil.e(TAG, "some fileds is empty!");
		}
	}

	void teamTransfer() {
		int sourceType = bundle.getInt(IntentConstant.INTENT_SOURCE_RESOURCE_TYPE);
		String sourceResourceID = bundle.getString(IntentConstant.INTENT_SOURCE_RESOURCE_ID);
		String sourceResourceOwnerID = bundle.getString(IntentConstant.INTENT_SOURCE_RESOURCE_OWNER);
		if (StringUtil.isNotBlank(sourceResourceID) && StringUtil.isNotBlank(sourceResourceOwnerID) && StringUtil.isNotBlank(currentFolderId)
				&& StringUtil.isNotBlank(currentOwnerId)) {
			if (sourceType == FileType.File.value()) {

				new ActionShare().copyShareFile(TargetFolderBrowserActivity.this, MessageCode.TRANSFER_TO_MY_FILE_SUCCESS, sourceResourceOwnerID,
						sourceResourceID, currentOwnerId, currentFolderId, msgHandler);
			} else if (sourceType == FileType.Folder.value()) {

				new ActionShare().copyShareFolder(TargetFolderBrowserActivity.this, MessageCode.TRANSFER_TO_MY_FILE_SUCCESS, sourceResourceOwnerID,
						sourceResourceID, currentOwnerId, currentFolderId, msgHandler);
			}
		} else {
			LogUtil.e(TAG, "some fileds is empty!");
		}

	}

	void fileTranslateTema() {
		ArrayList datas = (ArrayList) bundle.getSerializable("datas");

		if (datas == null || datas.isEmpty()) { // 单个文件的转存到团队空间
			int sourceType = bundle.getInt(IntentConstant.INTENT_SOURCE_RESOURCE_TYPE);
			FileFolderInfo info = (FileFolderInfo) bundle.getSerializable(IntentConstant.INTENT_DATA_EXTENDS_1);

			if (StringUtil.isNotBlank(currentFolderId) && StringUtil.isNotBlank(currentOwnerId)) {
				if (sourceType == FileType.File.value()) {
					new ActionShare().copyShareFile(TargetFolderBrowserActivity.this, MessageCode.TRANSFER_TO_MY_TEAM_SUCCESS, info.getOwnerId(), info.getId(),
							currentOwnerId, currentFolderId, msgHandler);

				} else if (sourceType == FileType.Folder.value()) {
					new ActionShare().copyShareFolder(TargetFolderBrowserActivity.this, MessageCode.TRANSFER_TO_MY_TEAM_SUCCESS, info.getOwnerId(),
							info.getId(), currentOwnerId, currentFolderId, msgHandler);
				}
			} else {

				LogUtil.e(TAG, "some fileds is empty!");
			}

		} else { // 多个文件转存到团队空间
			if (StringUtil.isNotBlank(currentFolderId) && StringUtil.isNotBlank(currentOwnerId)) {
				new NodeAction().saveToTeamSpace(TargetFolderBrowserActivity.this, msgHandler, UiConstant.NODES_ACTION_COPY_ALL_SUCCESS, datas,
						currentFolderId, currentOwnerId);
			} else {

				LogUtil.e(TAG, "some fileds is empty!");
			}

		}

	}

	@Override
	public void onBackPressed() {
		if (StringUtil.isBlank(currentOwnerId)) {
			if (intent == null) {
				intent = new Intent();
			}
			setResult(IntentConstant.INTENT_RESPONSE_SEARCH_TARGET_NULL, intent);
			finish();
			return;
		}

		if (displayResolve.getHistoryStack().size() > 1) {
			displayResolve.openParentFolder();
		} else {
			if (intent == null) {
				intent = new Intent();
			}
			setResult(IntentConstant.INTENT_RESPONSE_SEARCH_TARGET_NULL, intent);
			finish();
		}
	}
}
